<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>桔下小弈</title>
    <link rel="stylesheet" href="./css/common.css">
    <link rel="stylesheet" href="./css/game_room.css">
    <link rel="shortcut icon" href="./image/favicon.ico" type="image/x-icon">

</head>

<style>
    #user_prompts {
        display: flex;
        /* 开启Flex布局 */
        justify-content: space-between;
        /* 水平方向两端对齐 */
        align-items: center;
        /* 垂直方向居中对齐（可选） */
        gap: 10px;
        /* 标签间距，替代margin更高效 */
        width: 100%;
    }
</style>


<body>
    <div class="nav">战罢两奁分白黑 一枰何处有亏成</div>
    <div class="container">
        <div id="chess_area">
            <!-- 棋盘区域, 需要基于 canvas 进行实现 -->
            <canvas id="chess" width="1200px" height="600px"></canvas>
            <!-- 显示区域 -->
            <div id="user_prompts">
                <div id="screen">等待玩家连接中...</div>
            </div>
        </div>
        <div id="left_area">
            <div class="opponent-header">对手信息</div>
            <div id="oppoent_info">
                名称: <span id="opponent_name" class="opponent"></span><br />
                天梯分数: <span id="opponent_score" class="opponent"></span><br />
                总场次: <span id="opponent_total_count"></span><br />
                胜场: <span id="opponent_win_count"></span><br />
                胜率: <span id="opponent_win_percentage"></span><br />
            </div>
            <div id="chat_area">
                <div id="chat_show">
                    <p class="self_msg">你好！</p>
                    <p class="peer_msg">你好！</p>
                </div>
                <div id="msg_show">
                    <input type="text" id="chat_input" class="input-field" placeholder="输入消息...">
                    <button id="chat_button" class="btn">发送</button>
                </div>
            </div>
        </div>

    </div>
    <script>
        let chessBoard = [];
        let BOARD_COL = 40;
        let BOARD_ROW = 20;
        let chess = document.getElementById('chess');
        //获取chess控件区域2d画布
        let context = chess.getContext('2d');
        function initGame() {
            initBoard();
            // 直接绘制棋盘，不使用背景图片
            drawChessBoard();
        }
        function initBoard() {
            for (let i = 0; i < BOARD_COL; i++) {
                chessBoard[i] = [];
                for (let j = 0; j < BOARD_ROW; j++) {
                    chessBoard[i][j] = 0;
                }
            }
        }
        // 绘制棋盘网格线
        function drawChessBoard() {
            context.strokeStyle = "#BFBFBF";
            for (let i = 0; i < BOARD_COL; i++) {
                //横向的线条
                context.moveTo(15 + i * 30, 15);
                context.lineTo(15 + i * 30, 585);
                context.stroke();

            }
            for (let i = 0; i < BOARD_ROW; i++) {
                //纵向的线条
                context.moveTo(15, 15 + i * 30);
                context.lineTo(1185, 15 + i * 30);
                context.stroke();

            }
        }
        //绘制棋子
        function oneStep(i, j, isWhite) {
            if (i < 0 || j < 0) return;
            context.beginPath();
            context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
            context.closePath();
            //createLinearGradient() 方法创建放射状/圆形渐变对象
            var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
            if (!isWhite) {
                // 深色方：深电蓝→靛蓝（模拟电路板暗底色）
                gradient.addColorStop(0, "#0A2463");
                gradient.addColorStop(1, "#1E3B8A");
            } else {
                // 浅色方：脉冲黄→浅黄（模拟电子信号闪烁光效）
                gradient.addColorStop(0, "#FFD166");
                gradient.addColorStop(1, "#FFEEA9");
            }
            context.fillStyle = gradient;
            context.fill();
        }
        //棋盘区域的点击事件
        chess.onclick = function (e) {
            let x = e.offsetX;
            let y = e.offsetY;
            // 注意, 横坐标是列, 纵坐标是行
            // 这里是为了让点击操作能够对应到网格线上
            let col = Math.floor(x / 30);
            let row = Math.floor(y / 30);
            if (chessBoard[col][row] != 0) {
                return;
            }
            send_chess(col, row);
        }

        function send_chat_message() {
            let text_div = document.getElementById("chat_input");
            let message = text_div.value.trim();

            if (message === "") {
                return;
            }

            let info = {
                optype: "chat",
                uid: room_info.uid,
                message: message
            }
            ws_hdl.send(JSON.stringify(info));
        }
    </script>

    <script>
        let ws_url = "ws://" + location.host + "/room";

        let ws_hdl = new WebSocket(ws_url);
        let room_info;
        let is_me;
        let is_game_over = false;

        window.onbeforeunload = function () {
            ws_hdl.close();
        }
        initGame();

        ws_hdl.onclose = function () {
        };
        ws_hdl.onerror = function () {
            window.location.assign("./login.html");
        };
        ws_hdl.onopen = function () {
        };
        ws_hdl.onmessage = function (evt) {
            let info = JSON.parse(evt.data);
            console.log(evt);

            if (info.optype == "error") {
                window.location.assign("./login.html");
            }
            else if (info.optype == "room_ready") {
                room_info = info;
                is_me = (room_info.white_player == room_info.uid);
                initGame();
                set_screen(is_me);
                show_oppoent_info(info);
                return;
            }
            else if (info.optype == "put_chess") {
                if (info.result == false) {
                    alert(info.reason);
                    return;
                }

                if (info.winner == 0) {
                    let isWhite = (info.uid == room_info.white_player);
                    oneStep(info.col, info.row, isWhite);
                    chessBoard[info.col][info.row] = 1;
                    console.log("(" + info.col + "," + info.row + ")");
                    is_me = !is_me;
                    set_screen(is_me);
                    return;
                }

                if (info.reason == "五子连珠") {
                    let isWhite = (info.uid == room_info.white_player);
                    oneStep(info.col, info.row, isWhite);
                }

                is_game_over = true;
                let winner_id = info.winner;
                if (winner_id == room_info.uid) {
                    // alert("恭喜你赢了！");
                    let screen_div = document.getElementById("screen");
                    screen_div.innerHTML = info.reason;
                    screen_div.classList.add("game-over");
                }
                else {
                    // alert("很遗憾，你输了！");
                    let screen_div = document.getElementById("screen");
                    screen_div.innerHTML = "很遗憾，你输了！";
                    screen_div.classList.add("game-over");
                }

                // 添加退出按钮
                let exitButton = document.createElement("button");
                exitButton.id = "exit-button";
                exitButton.textContent = "返回大厅";
                exitButton.className = "btn";
                exitButton.addEventListener('click', function () {
                    window.location.assign("./game_hall.html");
                });
                document.getElementById("user_prompts").appendChild(exitButton);
            }
            else if (info.optype == "chat") {
                if (info.result == false) {
                    alert(info.reason);
                    return;
                }
                let chat_area_div = document.getElementById("chat_show");
                let mesg_div = document.createElement("div");
                mesg_div.textContent = info.message;

                if (info.uid == room_info.uid) {
                    mesg_div.classList.add("self_msg");
                    document.getElementById("chat_input").value = "";
                }
                else {
                    mesg_div.classList.add("peer_msg");
                }
                chat_area_div.appendChild(mesg_div);

                // 添加换行
                // chat_area_div.appendChild(document.createElement("br"));

                // 滚动到底部
                chat_area_div.scrollTop = chat_area_div.scrollHeight;
            }
        }

        function send_chess(c, r) {
            if (is_game_over) {
                alert("游戏结束, 可以退出房间");
                return;
            }
            if (!is_me) {
                alert("等待对方下棋...");
                return;
            }
            let chess_info = {
                optype: "put_chess",
                col: c,
                row: r,
                uid: room_info.uid,
            }
            ws_hdl.send(JSON.stringify(chess_info));
        }

        function set_screen(is_me) {
            let screen_div = document.getElementById("screen");
            if (is_me) {
                screen_div.innerHTML = "请下棋";
                // 添加闪烁动画效果
                screen_div.classList.add("blink");
                setTimeout(() => {
                    screen_div.classList.remove("blink");
                }, 1000);
            }
            else {
                screen_div.innerHTML = "等待对方下棋";
                screen_div.classList.remove("blink");
            }
        }

        function show_oppoent_info(info) {
            console.log(info);

            let _opponent_name = document.getElementById("opponent_name");
            let _opponent_score = document.getElementById("opponent_score");
            let _opponent_total_count = document.getElementById("opponent_total_count");
            let _opponent_win_count = document.getElementById("opponent_win_count");
            let _opponent_win_percentage = document.getElementById("opponent_win_percentage");

            _opponent_name.innerHTML = info.opponent_username;
            _opponent_score.innerHTML = info.opponent_score;
            _opponent_total_count.innerHTML = info.opponent_total_count;
            _opponent_win_count.innerHTML = info.opponent_win_count;

            const total = Number(info.opponent_total_count) || 0;
            const win = Number(info.opponent_win_count) || 0;
            const winRate = total === 0 ? "0%" : (win / total * 100).toFixed(1) + "%";

            _opponent_win_percentage.innerHTML = winRate;
        }

        // 为聊天按钮和输入框添加事件监听器
        document.getElementById("chat_button").addEventListener("click", send_chat_message);
        document.getElementById("chat_input").addEventListener("keyup", function (event) {
            if (event.key === "Enter") {
                send_chat_message();
            }
        });
    </script>

</body>

</html>